package com.hongkuncheng.cms.controller.admin;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hongkuncheng.cms.helper.SecurityHelper;
import org.hibernate.LockMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Controller;
import com.hongkuncheng.cms.controller.BaseController;
import com.hongkuncheng.cms.helper.HttpHelper;
import com.hongkuncheng.cms.helper.PageHelper;
import com.hongkuncheng.cms.helper.TokenHelper;
import com.hongkuncheng.cms.model.Organization;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 单位管理
 *
 * @author 洪坤成
 */
@Controller
@Transactional
@RequestMapping("admin/organization")
public class AorganizationController extends BaseController {

    // 单位列表
    @RequestMapping
    public String index() {
        List<Organization> organizations = factorySession.createCriteria(Organization.class)
                .addOrder(Order.asc("sort")).list();
        request.setAttribute("organizations", organizations);
        request.setAttribute("orgproject", applicationName);
        return view();
    }

    // 单位编辑
    @RequestMapping("edit")
    public String edit() {
        int organizationId = request.getParameter("organizationid") == null ? 0 :
                Integer.parseInt(request.getParameter("organizationid"));
        Organization organization = organizationId == 0 ? new Organization() :
                factorySession.get(Organization.class, organizationId);
        if (organizationId == 0) {
            Object uniqueResult = factorySession.createCriteria(Organization.class)
                    .setProjection(Projections.max("sort")).uniqueResult();
            int maxSort = uniqueResult == null ? 0 : Integer.parseInt(uniqueResult.toString());
            organization.setSort(++maxSort);
        }
        request.setAttribute("organization", organization);
        return view();
    }

    // 单位编辑处理
    @RequestMapping("editdo")
    @ResponseBody
    public void editdo() {
        checkAdminPermission("yunwei_organ_organization");
        int organizationId = Integer.parseInt(request.getParameter("organizationid"));
        String project = request.getParameter("project");
        int exist = Integer.parseInt(factorySession.createCriteria(Organization.class)
                .add(Restrictions.eq("project", project))
                .add(Restrictions.ne("id", organizationId))
                .setProjection(Projections.count("id"))
                .uniqueResult().toString());
        if (exist > 0) {
            PageHelper.alertAndGoBack("项目名称已存在，请重新输入");
            return;
        }
        String name = request.getParameter("name");
        exist = Integer.parseInt(factorySession.createCriteria(Organization.class)
                .add(Restrictions.eq("name", name))
                .add(Restrictions.ne("id", organizationId))
                .setProjection(Projections.count("id"))
                .uniqueResult().toString());
        if (exist > 0) {
            PageHelper.alertAndGoBack("单位名称已存在，请重新输入");
            return;
        }
        Organization organization = organizationId == 0 ? new Organization() :
                factorySession.load(Organization.class, organizationId, LockMode.PESSIMISTIC_WRITE);
        organization.setProject(project);
        organization.setName(name);
        organization.setOutterhost(request.getParameter("outterhost"));
        organization.setInnerhost(request.getParameter("innerhost"));
        if (organizationId == 0) organization.setAttach(true);
        organization.setSort(Integer.parseInt(request.getParameter("sort")));
        if (organizationId == 0) factorySession.save(organization);
        recordLog((organizationId == 0 ? "新建" : "更新") + "单位《" + organization.getName().trim() + "》");
        PageHelper.alertAndRedirect("保存成功", "./");
    }

    // 单位删除
    @RequestMapping("delete")
    @ResponseBody
    public void delete() {
        checkAdminPermission("yunwei_organ_organization");
        int organizationId = Integer.parseInt(request.getParameter("organizationid"));
        Organization organization = factorySession.load(Organization.class, organizationId, LockMode.PESSIMISTIC_WRITE);
        factorySession.delete(organization);
        recordLog("删除单位《" + organization.getName().trim() + "》");
        PageHelper.alertAndRedirect("删除成功", "./");
    }

    // 单位检测
    @RequestMapping("check")
    @ResponseBody
    public void check() {
        int organizationId = Integer.parseInt(request.getParameter("organizationid"));
        Organization organization = factorySession.get(Organization.class, organizationId);
        String result = HttpHelper.get(organization.getInnerhost() + "/interfaces/test");
        print(result.equals("callback is null"));
    }

    // 单位附加
    @RequestMapping("attach")
    @ResponseBody
    public void attach() {
        checkAdminPermission("yunwei_organ_organization");
        int organizationId = Integer.parseInt(request.getParameter("organizationid"));
        Organization organization = factorySession.load(Organization.class, organizationId, LockMode.PESSIMISTIC_WRITE);
        organization.setAttach(true);
        PageHelper.alertAndRedirect("附加成功", "./");
    }

    // 单位脱离
    @RequestMapping("deattach")
    @ResponseBody
    public void deattach() {
        checkAdminPermission("yunwei_organ_organization");
        int organizationId = Integer.parseInt(request.getParameter("organizationid"));
        Organization organization = factorySession.load(Organization.class, organizationId, LockMode.PESSIMISTIC_WRITE);
        if (!organization.getProject().equals(applicationName)) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("token", TokenHelper.generate());
            HttpHelper.post(organization.getInnerhost() + "/interfaces/organization/deattach", params);
        }
        // 如果脱离当前单位
        organization.setAttach(false);
        PageHelper.alertAndRedirect("脱离成功", "./");
    }

    // 重置管理员密码
    @RequestMapping("resetpassword")
    @ResponseBody
    public void resetpassword() {
        checkAdminPermission("yunwei_organ_organization");
        int organizationId = Integer.parseInt(request.getParameter("organizationid"));
        Organization organization = factorySession.load(Organization.class, organizationId);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("token", TokenHelper.generate());
        HttpHelper.post(organization.getInnerhost() + "/interfaces/organization/resetpassword", params);
        PageHelper.alertAndRedirect("重置密码成功，新密码为：123456", "./");
    }

    // 单点登录
    @RequestMapping("singlelogin")
    public String singlelogin() {
        checkAdminPermission("yunwei_organ_organization");
        int organizationId = Integer.parseInt(request.getParameter("organizationid"));
        Organization organization = factorySession.load(Organization.class, organizationId);
        request.setAttribute("organization", organization);
        request.setAttribute("token", TokenHelper.generate());
        request.setAttribute("windowheight", request.getSession().getAttribute("windowheight"));
        return view();
    }

    // 单位同步（供Ajax调用）
    @RequestMapping("synchronization")
    @ResponseBody
    public void synchronization() {
        checkAdminPermission("yunwei_organ_organization");
        int organizationId = Integer.parseInt(request.getParameter("organizationid"));
        Organization orgtarget = factorySession.load(Organization.class, organizationId);
        List<Organization> organizations = factorySession.createCriteria(Organization.class)
                .add(Restrictions.eq("attach", true)).list();
        JSONArray array = new JSONArray();
        for (Organization organization : organizations) {
            JSONObject object = new JSONObject();
            object.put("name", SecurityHelper.aesEncrypt(organization.getName()));
            object.put("project", SecurityHelper.aesEncrypt(organization.getProject()));
            object.put("outterhost", SecurityHelper.aesEncrypt(organization.getOutterhost()));
            object.put("innerhost", SecurityHelper.aesEncrypt(organization.getInnerhost()));
            array.add(object);
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("token", TokenHelper.generate());
        params.put("jsonstr", array.toString());
        String result = HttpHelper.post(orgtarget.getInnerhost() + "/interfaces/organization/update", params);
        print(result);
    }

}
